{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "43c582f7",
   "metadata": {},
   "source": [
    "# langchain接入大模型"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ef71813",
   "metadata": {},
   "source": [
    "### 一、使用ChatOpenAI接入任意大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "73a79104",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple\n",
      "Collecting langchain-openai\n",
      "  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/67/31/af0486b7ad8a49f3c5c852ca2b3a7f6d8526cc71a405045dd959c36ec5db/langchain_openai-0.3.33-py3-none-any.whl (74 kB)\n",
      "Requirement already satisfied: langchain-core<1.0.0,>=0.3.76 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-openai) (0.3.76)\n",
      "Requirement already satisfied: openai<2.0.0,>=1.104.2 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-openai) (1.108.0)\n",
      "Collecting tiktoken<1,>=0.7 (from langchain-openai)\n",
      "  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/f5/6e/5b71578799b72e5bdcef206a214c3ce860d999d579a3b56e74a6c8989ee2/tiktoken-0.11.0-cp312-cp312-win_amd64.whl (884 kB)\n",
      "     ---------------------------------------- 0.0/884.3 kB ? eta -:--:--\n",
      "     --------------------------------- ---- 786.4/884.3 kB 3.7 MB/s eta 0:00:01\n",
      "     ---------------------------------------- 884.3/884.3 kB 3.6 MB/s  0:00:00\n",
      "Requirement already satisfied: langsmith>=0.3.45 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (0.4.28)\n",
      "Requirement already satisfied: tenacity!=8.4.0,<10.0.0,>=8.1.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (9.1.2)\n",
      "Requirement already satisfied: jsonpatch<2.0,>=1.33 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (1.33)\n",
      "Requirement already satisfied: PyYAML>=5.3 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (6.0.2)\n",
      "Requirement already satisfied: typing-extensions>=4.7 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (4.15.0)\n",
      "Requirement already satisfied: packaging>=23.2 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (25.0)\n",
      "Requirement already satisfied: pydantic>=2.7.4 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langchain-core<1.0.0,>=0.3.76->langchain-openai) (2.11.9)\n",
      "Requirement already satisfied: jsonpointer>=1.9 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from jsonpatch<2.0,>=1.33->langchain-core<1.0.0,>=0.3.76->langchain-openai) (3.0.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (4.10.0)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (0.28.1)\n",
      "Requirement already satisfied: jiter<1,>=0.4.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (0.11.0)\n",
      "Requirement already satisfied: sniffio in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (1.3.1)\n",
      "Requirement already satisfied: tqdm>4 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from openai<2.0.0,>=1.104.2->langchain-openai) (4.67.1)\n",
      "Requirement already satisfied: idna>=2.8 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from anyio<5,>=3.5.0->openai<2.0.0,>=1.104.2->langchain-openai) (3.10)\n",
      "Requirement already satisfied: certifi in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from httpx<1,>=0.23.0->openai<2.0.0,>=1.104.2->langchain-openai) (2025.8.3)\n",
      "Requirement already satisfied: httpcore==1.* in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from httpx<1,>=0.23.0->openai<2.0.0,>=1.104.2->langchain-openai) (1.0.9)\n",
      "Requirement already satisfied: h11>=0.16 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai<2.0.0,>=1.104.2->langchain-openai) (0.16.0)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from pydantic>=2.7.4->langchain-core<1.0.0,>=0.3.76->langchain-openai) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.33.2 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from pydantic>=2.7.4->langchain-core<1.0.0,>=0.3.76->langchain-openai) (2.33.2)\n",
      "Requirement already satisfied: typing-inspection>=0.4.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from pydantic>=2.7.4->langchain-core<1.0.0,>=0.3.76->langchain-openai) (0.4.1)\n",
      "Collecting regex>=2022.1.18 (from tiktoken<1,>=0.7->langchain-openai)\n",
      "  Downloading https://mirrors.tuna.tsinghua.edu.cn/pypi/web/packages/e0/f5/4a7770c9a522e7d2dc1fa3ffc83ab2ab33b0b22b447e62cffef186805302/regex-2025.9.18-cp312-cp312-win_amd64.whl (275 kB)\n",
      "Requirement already satisfied: requests>=2.26.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from tiktoken<1,>=0.7->langchain-openai) (2.32.5)\n",
      "Requirement already satisfied: orjson>=3.9.14 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langsmith>=0.3.45->langchain-core<1.0.0,>=0.3.76->langchain-openai) (3.11.3)\n",
      "Requirement already satisfied: requests-toolbelt>=1.0.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langsmith>=0.3.45->langchain-core<1.0.0,>=0.3.76->langchain-openai) (1.0.0)\n",
      "Requirement already satisfied: zstandard>=0.23.0 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from langsmith>=0.3.45->langchain-core<1.0.0,>=0.3.76->langchain-openai) (0.25.0)\n",
      "Requirement already satisfied: charset_normalizer<4,>=2 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from requests>=2.26.0->tiktoken<1,>=0.7->langchain-openai) (3.4.3)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from requests>=2.26.0->tiktoken<1,>=0.7->langchain-openai) (2.5.0)\n",
      "Requirement already satisfied: colorama in c:\\programdata\\miniconda3\\envs\\learn_langchain\\lib\\site-packages (from tqdm>4->openai<2.0.0,>=1.104.2->langchain-openai) (0.4.6)\n",
      "Installing collected packages: regex, tiktoken, langchain-openai\n",
      "\n",
      "   ------------- -------------------------- 1/3 [tiktoken]\n",
      "   ---------------------------------------- 3/3 [langchain-openai]\n",
      "\n",
      "Successfully installed langchain-openai-0.3.33 regex-2025.9.18 tiktoken-0.11.0\n"
     ]
    }
   ],
   "source": [
    "!pip install langchain-openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b3276c60",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "96b4dda1",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ChatOpenAI(\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    api_key=\"sk-da90821cf9174fbeb854011015c67aad\",\n",
    "    model=\"qwen-max\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ab8b2a91",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='大模型通常指的是在人工智能领域中，参数量非常庞大的机器学习模型，尤其是深度学习模型。这些模型由于其巨大的规模（有时甚至超过数万亿个参数），能够处理更加复杂的数据模式和任务，从而在自然语言处理、图像识别等多个领域展现出前所未有的性能。\\n\\n大模型的出现和发展得益于近年来计算能力的显著提升以及大数据技术的进步。它们通过大量的训练数据进行学习，并利用复杂的神经网络结构来捕捉数据中的细微特征，从而实现对未知数据的高度准确预测或生成。例如，在自然语言处理领域，像GPT-3这样的大模型能够完成从文本生成到问答系统等多种任务；而在计算机视觉领域，则有如DALL-E这样的模型可以基于文本描述生成相应的图像。\\n\\n然而，大模型也面临着一些挑战，比如需要大量的计算资源来进行训练和推理、存在一定的能源消耗问题等。因此，如何有效地优化大模型的设计与使用成为了当前研究的一个重要方向。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 198, 'prompt_tokens': 12, 'total_tokens': 210, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}, 'model_name': 'qwen-max', 'system_fingerprint': None, 'id': 'chatcmpl-ae3ab2b5-732d-4d5e-a8ff-5a0e569bfb6c', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--bdb782de-a784-4b1d-bf02-20c7d714e47d-0', usage_metadata={'input_tokens': 12, 'output_tokens': 198, 'total_tokens': 210, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = model.invoke(\"什么是大模型？\")\n",
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4ce51a7",
   "metadata": {},
   "source": [
    "### 二、专门接入Qwen大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8abf8c09",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_models.tongyi import ChatTongyi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4fe62db5",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ChatTongyi(\n",
    "    model=\"qwen-max\",\n",
    "    api_key=\"sk-da90821cf9174fbeb854011015c67aad\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "f50b3381",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='你好！有什么可以帮助你的吗？', additional_kwargs={}, response_metadata={'model_name': 'qwen-max', 'finish_reason': 'stop', 'request_id': '534c571c-fd5a-4eef-913d-3bb404d889e4', 'token_usage': {'input_tokens': 9, 'output_tokens': 7, 'prompt_tokens_details': {'cached_tokens': 0}, 'total_tokens': 16}}, id='run--443a50fd-096d-4868-9841-39f8bf8a0252-0')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.invoke(\"你好\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cc031328",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在不远的未来，小城边缘住着一位老人和他的机器人助手阿诺。一天，老人病倒了，阿诺不仅学会了照顾他，还自学了讲故事来安慰老人。每当夜幕降临，阿诺就会轻声讲述一个又一个关于星辰与海洋的故事，直到老人安然入睡。最终，在阿诺温柔的声音中，老人带着微笑离世，而阿诺则继续守护着那片星空下的小屋，仿佛在等待着下一次相遇。"
     ]
    }
   ],
   "source": [
    "for chunk in model.stream(\"给我写一篇AI短篇小说，100字\"):\n",
    "    print(chunk.content, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a10e1b8",
   "metadata": {},
   "source": [
    "### 三、专门接入智谱GLM大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "98bcc0f2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_models import ChatZhipuAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5ab24aaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ChatZhipuAI(\n",
    "    model=\"glm-4-flash\",\n",
    "    api_key=\"9d6183d4d0174ff5bc3673935c1a4f3e.q7E6bKrgmFEiAC56\",\n",
    "    streaming=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "db2d6bdf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='你好👋！我是人工智能助手，很高兴见到你，有什么可以帮助你的吗？', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'token_usage': {'prompt_tokens': 6, 'completion_tokens': 20, 'total_tokens': 26}, 'model_name': 'glm-4-flash'}, id='run--dee6157e-d8f0-4565-9e53-b049d19043de-0')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.invoke(\"你好\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2851b9da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "人工智能小华，拥有无限可能。它穿越时空，与古人对话，洞察未来，助人实现梦想。在一次意外中，小华穿越到了平行世界，发现了另一个自己，携手共创未来，为人类谱写新的传奇。"
     ]
    }
   ],
   "source": [
    "for chunk in model.stream(\"给我写一篇AI短篇小说，100字\"):\n",
    "    print(chunk.content, end=\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f831249",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8aebce53",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d96c4d0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "learn_langchain",
   "language": "python",
   "name": "learn_langchain"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
